import json
from datetime import datetime

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from .models import SysMenu, SysMenuSerializer, SysRoleMenu


# Create your views here.
class TreeListView(View):
    # 构造菜单树
    def pre_menus(self, menus_data):
        menus = []
        if len(menus_data) > 0:
            for i in menus_data:
                if i['parent_id'] == 0:
                    menus.append(i)

            for idx, item in enumerate(menus):
                child = []
                for j in menus_data:
                    if j['parent_id'] == item['id']:
                        child.append(j)
                item['children'] = child
                menus[idx] = item
        return menus

    def get(self, request):
        menuQuerySet = SysMenu.objects.order_by("order_num").values()
        # 构造菜单树
        sysMenuList = self.pre_menus(menuQuerySet)
        return JsonResponse(
            {'code': 200, 'treeList': sysMenuList})


# 根据角色查询菜单权限
class MenusView(View):
    def get(self, request):
        id = request.GET.get("id")
        menuList = SysRoleMenu.objects.filter(role_id=id).values("menu_id")
        menuIdList = [m['menu_id'] for m in menuList]
        return JsonResponse(
            {'code': 200, 'menuIdList': menuIdList})


class SaveView(View):
    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        if data['id'] == -1:  # 添加
            obj_sysMenu = SysMenu(name=data['name'], icon=data['icon'],
                                  parent_id=data['parent_id'],
                                  order_num=data['order_num'], path=data['path'],
                                  component=data['component'],
                                  menu_type=data['menu_type'], perms=data['perms'],
                                  method=data['method'], href=data['href'],
                                  remark=data['remark'])
            obj_sysMenu.create_time = datetime.now().date()
            obj_sysMenu.save()
        else:  # 修改
            obj_sysMenu = SysMenu(id=data['id'], name=data['name'],
                                  icon=data['icon'],
                                  parent_id=data['parent_id'],
                                  order_num=data['order_num'], path=data['path'],
                                  component=data['component'],
                                  menu_type=data['menu_type'], perms=data['perms'],
                                  method=data['method'], href=data['href'],
                                  remark=data['remark'],
                                  create_time=data['create_time'],
                                  update_time=data['update_time'])
            obj_sysMenu.update_time = datetime.now().date()
            obj_sysMenu.save()
        return JsonResponse({'code': 200})


# 菜单基本操作
class ActionView(View):
    def get(self, request):
        """
        根据id获取权限信息
        :param request:
        :return:
        """
        id = request.GET.get("id")
        menu_object = SysMenu.objects.get(id=id)
        return JsonResponse({'code': 200, 'menu':
            SysMenuSerializer(menu_object).data})

    def delete(self, request):
        """
        删除操作
        :param request:
        :return:
        """

        id = json.loads(request.body.decode("utf-8"))
        if SysMenu.objects.filter(parent_id=id).count() > 0:
            return JsonResponse({'code': 500, 'msg': '请先删除子菜单！'})
        else:
            SysRoleMenu.objects.filter(menu_id=id).delete()
        SysMenu.objects.get(id=id).delete()
        return JsonResponse({'code': 200})
